package com.hnd.springframerwork.context.support;

import cn.hutool.core.bean.BeanException;
import com.hnd.springframerwork.beans.factory.BeanFactory;
import com.hnd.springframerwork.beans.factory.ConfigurableListableBeanFactory;
import com.hnd.springframerwork.beans.factory.config.BeanFactoryPostProcessor;
import com.hnd.springframerwork.beans.factory.config.BeanPostProcessor;
import com.hnd.springframerwork.context.ConfigurableApplicationContext;
import com.hnd.springframerwork.core.io.DefaultResourceLoader;

import java.util.Map;

/**
 * 模板：固定刷新流程，开放刷新操作
 */
public abstract class AbstractApplicationContext  extends DefaultResourceLoader implements ConfigurableApplicationContext {
    @Override
    public void refresh() {
        refeshBeanFactory();
        ConfigurableListableBeanFactory beanFactory = getBeanFactory();
        invokeBeanFactoryProsProcessors(beanFactory);
        registerBeanProcessors(beanFactory);
        beanFactory.preInstantiateSingletons();
    }

    protected abstract void refeshBeanFactory() throws BeanException;

    protected abstract ConfigurableListableBeanFactory getBeanFactory();



  private void invokeBeanFactoryProsProcessors(ConfigurableListableBeanFactory factory){
      Map<String, BeanFactoryPostProcessor> beanFactoryPostProcessorMap = factory.getBeanOfType(BeanFactoryPostProcessor.class);
      for (BeanFactoryPostProcessor beanFactoryPostProcessor : beanFactoryPostProcessorMap.values()) {
          beanFactoryPostProcessor.postProcessBeanFactory(factory);

      }

  }

    private void registerBeanProcessors(ConfigurableListableBeanFactory beanFactory) {
        Map<String, BeanPostProcessor> beanPostProcessorMap = beanFactory.getBeanOfType(BeanPostProcessor.class);
        beanPostProcessorMap.values().forEach(x->beanFactory.addBeanPostProcessor(x));
    }

    @Override
    public <T> Map<String, T> getBeanOfType(Class<T> type) {
        return getBeanFactory().getBeanOfType(type);
    }

    @Override
    public String[] getBeanDefinitionNames() {
        return getBeanFactory().getBeanDefinitionNames();
    }

    @Override
    public Object getBean(String beanName) {
        return getBeanFactory().getBean(beanName);
    }

    @Override
    public Object getBean(String beanName, Object... args) {
        return getBeanFactory().getBean(beanName,args);
    }

    @Override
    public <T> T getBean(String beanName, Class<T> requireType) {
        return getBeanFactory().getBean(beanName,requireType);
    }
}
